using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Interop;
using System.Windows.Markup;
using System.Windows.Media.Imaging;
using Common;
using Common.Enum;
using Common.NotifyEvent;
using Controls;
using Converters;
using Define;
using device;
using MainView.View;
using MainView.Windows;
using Microsoft.Win32;
using ProjectView.Windows;
using SettingsView;
using SettingsView.Search;
using SExperiment;
using SSettings;
using SSettings.SoftSetting;

namespace MainView
{
	public partial class MainWindow : Window, IComponentConnector
	{
		public struct CopyDataStruct
		{
			public IntPtr dwData;

			public int cbData;

			[MarshalAs(UnmanagedType.LPStr)]
			public string lpData;
		}

		public delegate void DelegateOnUCExperimentOpenFileEvent();

		public static ObservableCollection<Experiment> ExperimentList = new ObservableCollection<Experiment>();

		private static string datPath = Utility.GetApplicationPath() + "data.dat";

		private bool isloaded;

		private List<string> uriList = new List<string>();

		private BackgroundWorker worker;

		public event DelegateOnUCExperimentOpenFileEvent OnUCExperimentOpenFile;

		private IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
		{
			if (74 == msg)
			{
				CopyDataStruct copyDataStruct = (CopyDataStruct)Marshal.PtrToStructure(lParam, typeof(CopyDataStruct));
				if (copyDataStruct.lpData.Length > 0)
				{
					OpenPcrFile(copyDataStruct.lpData);
				}
				base.WindowState = WindowState.Maximized;
				Activate();
			}
			return hwnd;
		}

		protected override void OnSourceInitialized(EventArgs e)
		{
			base.OnSourceInitialized(e);
			HwndSource hwndSource = PresentationSource.FromVisual(this) as HwndSource;
			if (hwndSource != null)
			{
				IntPtr handle = hwndSource.Handle;
				hwndSource.AddHook(WndProc);
			}
		}

		public void OpenExperimentFromHomeControl(string path, bool IsHistory = true, string defaultPath = "")
		{
			if (IsHistory)
			{
				OpenExperiment(path);
				return;
			}
			Experiment experiment = CreateExperiment(path, false);
			if (experiment != null)
			{
				experiment.Status = EExperimentStatus.AbnormalInterrupt;
				if (!string.IsNullOrEmpty(defaultPath))
				{
					experiment.DefaultPath = defaultPath;
				}
				CreateNewTabItem(experiment);
			}
		}

		public void CreateExperimentFromHomeControl(EExperimentCreateMode createMode)
		{
			CreateExperiment(createMode);
		}

		private void SetLOGO()
		{
			string path = Utility.GetApplicationPath() + "LOGO.png";
			if (File.Exists(path))
			{
				try
				{
					FileStream fileStream = new FileStream(Utility.GetApplicationPath() + "LOGO.png", FileMode.Open, FileAccess.Read);
					byte[] array = new byte[fileStream.Length];
					fileStream.Read(array, 0, array.Length);
					fileStream.Close();
					fileStream.Dispose();
					MemoryStream streamSource = new MemoryStream(array);
					BitmapImage bitmapImage = new BitmapImage();
					bitmapImage.BeginInit();
					bitmapImage.StreamSource = streamSource;
					bitmapImage.EndInit();
					Logo.Source = bitmapImage;
				}
				catch (Exception)
				{
				}
			}
		}

		public MainWindow()
		{
			InitializeComponent();
			SetLOGO();
			base.ResizeMode = ResizeMode.CanMinimize;
			base.WindowStyle = WindowStyle.None;
			AddHandler(ProjectManageWindow.OnProjectIsUsingRoutedEvent, new RoutedEventHandler(OnProjectIsUsing_RoutedEvent), true);
			AddHandler(UCExperiment.OnExperimentStatusChangedRoutedEvent, new RoutedEventHandler(OnExperimentStatusChanged_RoutedEvent), true);
			AddHandler(UCSearchWellInfo.OnSearchExperimentOpenChangedRoutedEvent, new RoutedEventHandler(searchView_OnOpenExperiment), true);
			if (ConfigReader.GetInstance().GetProjectConfigFromIni() == 1)
			{
				tabProject.Visibility = Visibility.Collapsed;
			}
			IList<string> list = Directory.GetFiles(Utility.GetTempPath(), "temp*" + Experiment.BakExt, SearchOption.TopDirectoryOnly).ToList();
			foreach (string item in list)
			{
				ExperimentTemporary experimentTemporaryInfo = Experiment.GetExperimentTemporaryInfo(item);
				if (experimentTemporaryInfo == null)
				{
					continue;
				}
				EExperimentStatus status = experimentTemporaryInfo.Status;
				string breakPoint = experimentTemporaryInfo.BreakPoint;
				if (status == EExperimentStatus.Running)
				{
					Experiment experiment = Experiment.Load(item, false);
					experiment.Name = experiment.Name.Remove(0, 4);
					experiment.DefaultPath = Utility.GetExperimentPath();
					experiment.TempFile = item;
					string messageBoxText = string.Format(Utility.GetMessage("msg_exist_experiment_abnormal"), experiment.Name, breakPoint);
					if (MessageBox.Show(messageBoxText, Utility.GetMessage("Warning"), MessageBoxButton.YesNo, MessageBoxImage.Exclamation, MessageBoxResult.Yes) == MessageBoxResult.Yes)
					{
						experiment.Status = EExperimentStatus.AbnormalInterrupt;
						CreateNewTabItem(experiment);
						continue;
					}
					experiment.Status = EExperimentStatus.Completed;
					if (experiment.CanSave())
					{
						experiment.Save(experiment.FilePath);
						CreateNewTabItem(experiment);
					}
					continue;
				}
				try
				{
					if (File.Exists(item))
					{
						File.Delete(item);
					}
				}
				catch
				{
				}
			}
			ucSettingMain.DataContext = ConfigSettings.GetInstance();
			Application.Current.MainWindow = this;
			Utility.RepairWindowBehavior(this);
			linkAboutTitle.Text = ConfigReader.GetInstance().GetLIS_TitleFromIni();
			string text = ConfigReader.GetInstance().GetLIS_AddressIni();
			if (text.ToUpper().IndexOf("HTTP://") == -1)
			{
				text = "http://" + text;
			}
			try
			{
				linkAbout.NavigateUri = new Uri(text, UriKind.Absolute);
			}
			catch (Exception)
			{
			}
		}

		private void searchView_OnOpenExperiment(object sender, RoutedEventArgs e)
		{
			OpenExperiment(e.OriginalSource.ToString());
			Experimenttab.IsSelected = true;
		}

		private void OnExperimentStatusChanged_RoutedEvent(object sender, RoutedEventArgs e)
		{
			if (ExperimentList.Where((Experiment s) => s.Status == EExperimentStatus.Running).Count() > 0)
			{
				Utility.PreventSleep();
			}
			else
			{
				Utility.ResotreSleep();
			}
		}

		private void OnProjectIsUsing_RoutedEvent(object sender, RoutedEventArgs e)
		{
			ProjectRoutedEventArgs args = e as ProjectRoutedEventArgs;
			if (args == null)
			{
				return;
			}
			Experiment experiment = ExperimentList.Where((Experiment s) => s.Wells.Where((Well s1) => s1.Project == args.Project).Count() > 0).FirstOrDefault();
			if (experiment != null)
			{
				args.IsUsing = true;
				args.ExperimentName = experiment.Name;
			}
		}

		private void Root_Closing(object sender, CancelEventArgs e)
		{
			if (ExperimentList.Where((Experiment s) => s.Status != EExperimentStatus.Completed && s.Device.RunState != 0 && s.Device.RunState != RunningState.Interrupt && s.Device.RunState != RunningState.Finish).Count() > 0)
			{
				MessageBox.Show(Utility.GetMessage("msg_close_experiment_confirm_running"));
				e.Cancel = true;
				return;
			}
			for (int num = TabControlExperiment.Items.Count - 1; num > 0; num--)
			{
				UCExperiment uCExperiment = ((TabItem)TabControlExperiment.Items[num]).Content as UCExperiment;
				if (!uCExperiment.Close())
				{
					e.Cancel = true;
					return;
				}
			}
			if (!ProjectManageWindow.Close())
			{
				e.Cancel = true;
			}
		}

		public static Experiment CreateNewExperiment(string path = null, bool isCvs = false)
		{
			return CreateExperimentEx(null, path);
		}

		private Experiment CreateExperiment(string path = null, bool saveHistory = true, bool isCvs = false)
		{
			return CreateExperimentEx(TabControlExperiment, path, saveHistory, isCvs);
		}

		private static Experiment CreateExperimentEx(TabControl tabControl, string path = null, bool saveHistory = true, bool isCvs = false)
		{
			Experiment experiment = new Experiment();
			if (string.IsNullOrEmpty(path))
			{
				experiment = new Experiment();
			}
			else
			{
				experiment = ((!isCvs) ? Experiment.LoadTemplate(path, saveHistory) : Experiment.LoadExperimentFromCsv(path));
				if (experiment == null)
				{
					if (!isCvs)
					{
						MessageBox.Show(Utility.GetMessage("msg_read_experiment_template_failure"));
					}
					return null;
				}
			}
			bool flag = false;
			List<RS232Port> list = (from s in Device.GetRS232PortInfo()
				where s.PortState == 0 || s.PortState == 1
				select s).ToList();
			if (list.Count == 0)
			{
				do
				{
					DeviceNotFoundWindow deviceNotFoundWindow = new DeviceNotFoundWindow();
					deviceNotFoundWindow.Owner = Utility.GetMainWindow();
					if (deviceNotFoundWindow.Owner == null)
					{
						deviceNotFoundWindow.ShowInTaskbar = true;
						deviceNotFoundWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
					}
					deviceNotFoundWindow.ShowDialog();
					if (deviceNotFoundWindow.DialogResult == DeviceNotFoundWindow.EDialogResult.VirtualDevice || (deviceNotFoundWindow.Owner == null && deviceNotFoundWindow.DialogResult == DeviceNotFoundWindow.EDialogResult.Close))
					{
						flag = true;
						break;
					}
					if (deviceNotFoundWindow.DialogResult == DeviceNotFoundWindow.EDialogResult.Retry)
					{
						list = (from s in Device.GetRS232PortInfo()
							where s.PortState == 0 || s.PortState == 1
							select s).ToList();
						continue;
					}
					return null;
				}
				while (list.Count <= 0);
			}
			if (!flag)
			{
				list = list.Where((RS232Port s) => s.PortState == 0 || (s.DeviceModel != Device.DeviceModel_48P && s.DeviceModel != Device.DeviceModel_24P && s.PortState == 1 && (s.BlockAState == 0 || s.BlockBState == 0))).ToList();
				if (list.Count == 0)
				{
					MessageBox.Show(Utility.GetMessage("msg_cannot_create_experimetn_use_model_A_B"));
					return null;
				}
			}
			int num = -1;
			if (list.Count == 1)
			{
				num = 0;
			}
			else if (list.Count > 1)
			{
				DeviceSelectorWindow deviceSelectorWindow = new DeviceSelectorWindow();
				deviceSelectorWindow.Owner = Utility.GetMainWindow();
				if (deviceSelectorWindow.Owner == null)
				{
					deviceSelectorWindow.ShowInTaskbar = true;
					deviceSelectorWindow.WindowStartupLocation = WindowStartupLocation.CenterScreen;
				}
				deviceSelectorWindow.ExperimentList = ExperimentList;
				deviceSelectorWindow.Ports = list;
				if (deviceSelectorWindow.ShowDialog() != true)
				{
					return null;
				}
				num = deviceSelectorWindow.SelectedIndex;
			}
			if (num >= 0 && num < list.Count)
			{
				experiment.Device.PortName = list[num].PortObject.PortName;
				experiment.Device.Model = list[num].DeviceModel;
				experiment.Device.Series = list[num].DeviceNo;
				experiment.Device.ChannelNo = list[num].Filter;
				experiment.Device.Company = list[num].Company;
				experiment.Device.Fast = list[num].Fast;
				int num2 = 0;
				if (tabControl != null)
				{
					foreach (TabItem item in (IEnumerable)tabControl.Items)
					{
						if (!(item.Content is UCExperiment))
						{
							continue;
						}
						Experiment experiment2 = ((UCExperiment)item.Content).Experiment;
						if (string.IsNullOrEmpty(experiment2.Device.Series) || experiment2.Status == EExperimentStatus.Completed || !(experiment2.Device.Series == experiment.Device.Series))
						{
							continue;
						}
						if (!string.IsNullOrEmpty(path))
						{
							if (experiment2.UseModelA && experiment.UseModelA)
							{
								MessageBox.Show(string.Format(Utility.GetMessage("msg_cannot_create_experimetn_model_using"), "A"));
								return null;
							}
							if (experiment2.UseModelB && experiment.UseModelB)
							{
								MessageBox.Show(string.Format(Utility.GetMessage("msg_cannot_create_experimetn_model_using"), "B"));
								return null;
							}
						}
						else
						{
							if (num2++ > 0 || experiment2.IsUseAllModel())
							{
								MessageBox.Show(Utility.GetMessage("msg_cannot_create_experimetn_use_model_A_B"));
								return null;
							}
							if (experiment.Type == EProjectType.Melt && (!experiment.UseModelA || !experiment.UseModelB))
							{
								MessageBox.Show(string.Format(Utility.GetMessage("msg_experiment_type_change_must_AB"), EnumManagement.GetProjectTypeName(EProjectType.Melt)));
								return null;
							}
						}
						experiment.CanUseModelA = !experiment2.UseModelA;
						experiment.CanUseModelB = !experiment2.UseModelB;
						experiment2.CanUseModelA = !experiment.CanUseModelA;
						experiment2.CanUseModelB = !experiment.CanUseModelB;
					}
				}
			}
			return experiment;
		}

		private void CreateExperiment(EExperimentCreateMode mode)
		{
			Experiment experiment = null;
			switch (mode)
			{
			case EExperimentCreateMode.Guid:
				experiment = CreateExperiment();
				if (experiment != null)
				{
					CreateNewTabItem(experiment);
				}
				break;
			case EExperimentCreateMode.Template:
			{
				OpenFileDialog openFileDialog = new OpenFileDialog();
				openFileDialog.Filter = string.Format("{0}{1}|*.{2}", Experiment.FileTemplateExt, Utility.GetMessage("File"), Experiment.FileTemplateExt);
				openFileDialog.FileName = string.Empty;
				openFileDialog.FilterIndex = 1;
				openFileDialog.InitialDirectory = Utility.GetExperimentTemplatePath();
				openFileDialog.DefaultExt = Experiment.FileTemplateExt;
				if (openFileDialog.ShowDialog() == true)
				{
					experiment = CreateExperiment(openFileDialog.FileName);
					if (experiment != null)
					{
						CreateNewTabItem(experiment);
					}
				}
				break;
			}
			case EExperimentCreateMode.OpenFile:
			{
				OpenFileDialog openFileDialog = new OpenFileDialog();
				openFileDialog.Filter = string.Format("{0}{1}|*.{2}", Experiment.FileExt, Utility.GetMessage("File"), Experiment.FileExt);
				openFileDialog.FileName = string.Empty;
				openFileDialog.Multiselect = true;
				openFileDialog.FilterIndex = 1;
				openFileDialog.RestoreDirectory = true;
				openFileDialog.DefaultExt = Experiment.FileExt;
				string experimentInitialDirectory = ConfigReader.GetInstance().GetExperimentInitialDirectory();
				try
				{
					openFileDialog.InitialDirectory = experimentInitialDirectory;
				}
				catch (Exception)
				{
				}
				if (openFileDialog.ShowDialog() != true)
				{
					break;
				}
				string directoryName = Path.GetDirectoryName(openFileDialog.FileName);
				if (!directoryName.Equals(experimentInitialDirectory))
				{
					ConfigReader.GetInstance().SetExperimentInitialDirectory(directoryName);
				}
				string[] fileNames = openFileDialog.FileNames;
				string[] array = fileNames;
				foreach (string path in array)
				{
					experiment = Experiment.Load(path);
					if (experiment != null)
					{
						experiment.Status = EExperimentStatus.Completed;
						CreateNewTabItem(experiment);
						if (this.OnUCExperimentOpenFile != null)
						{
							this.OnUCExperimentOpenFile();
						}
					}
					else
					{
						MessageBox.Show(Utility.GetMessage("msg_load_experiment_fail"));
					}
				}
				break;
			}
			case EExperimentCreateMode.Last:
				experiment = CreateExperiment(Experiment.LastTempateName, false);
				if (experiment != null)
				{
					CreateNewTabItem(experiment).SelectExperimentRun();
				}
				break;
			case EExperimentCreateMode.WellPlate:
			{
				string text = Utility.GetSystemTempFile();
				BasicSetting basicSetting = ConfigSettings.GetInstance().BasicSetting;
				if (basicSetting.CustomImport)
				{
					if (!File.Exists(basicSetting.CustomImportFullName))
					{
						MessageBox.Show(Utility.GetMessage("msg_notset_customimportfile"));
						break;
					}
					Process process = Process.Start(basicSetting.CustomImportFullName, "\"" + text + "\"");
					process.WaitForExit();
					if (!File.Exists(text))
					{
						break;
					}
				}
				else
				{
					OpenFileDialog openFileDialog = new OpenFileDialog();
					openFileDialog.Filter = string.Format("{0}{1}|*.{2}", "csv", Utility.GetMessage("File"), "csv");
					openFileDialog.FileName = string.Empty;
					openFileDialog.FilterIndex = 1;
					openFileDialog.InitialDirectory = Utility.GetExperimentPath();
					openFileDialog.DefaultExt = Experiment.FileExt;
					if (openFileDialog.ShowDialog() != true)
					{
						break;
					}
					text = openFileDialog.FileName;
				}
				experiment = CreateExperiment(text, false, true);
				if (experiment != null)
				{
					CreateNewTabItem(experiment).SelectExperimentRun();
				}
				break;
			}
			case EExperimentCreateMode.Quick:
				break;
			}
		}

		public static bool Validate(Experiment experiment)
		{
			bool result = true;
			if (!File.Exists(datPath))
			{
				MessageBox.Show(Utility.GetMessage("msg_dat_file_not_found"), Utility.GetMessage("Warning"), MessageBoxButton.OK);
				result = false;
			}
			else if (!string.IsNullOrEmpty(experiment.Device.Model) && !experiment.CheckDatFile())
			{
				MessageBox.Show(Utility.GetMessage("msg_validate_device_failed"), Utility.GetMessage("Warning"), MessageBoxButton.OK);
				result = false;
			}
			return result;
		}

		private UCExperiment CreateNewTabItem(Experiment experiment)
		{
			if (!Validate(experiment))
			{
				return null;
			}
			Experiment experiment2 = null;
			if (!string.IsNullOrEmpty(experiment.FilePath) && (experiment2 = ExperimentList.Where((Experiment s) => s.FilePath == experiment.FilePath).FirstOrDefault()) != null)
			{
				foreach (TabItem item in (IEnumerable)TabControlExperiment.Items)
				{
					if (item is TabItemCloseable && item.Content is UCExperiment && ((UCExperiment)item.Content).Experiment == experiment2)
					{
						item.IsSelected = true;
						return (UCExperiment)item.Content;
					}
				}
			}
			UCExperiment uCExperiment = new UCExperiment(experiment);
			experiment.Event += experiment_Event;
			uCExperiment.OnExperimentNew += window_OnExperimentNew;
			uCExperiment.OnWindowClose += window_OnWindowClose;
			TabItemCloseable tabItemCloseable = new TabItemCloseable();
			tabItemCloseable.Style = Utility.GetResource("TabItemCloseableStyleDefault") as Style;
			tabItemCloseable.CloseTab += item_CloseTab;
			tabItemCloseable.IsSelected = true;
			tabItemCloseable.Content = uCExperiment;
			MultiBinding multiBinding = new MultiBinding();
			multiBinding.Converter = new TabItemExperimentNameMultiConverter();
			multiBinding.Bindings.Add(new Binding("Name")
			{
				Source = experiment,
				UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
			});
			multiBinding.Bindings.Add(new Binding("Status")
			{
				Source = experiment,
				UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged
			});
			tabItemCloseable.SetBinding(HeaderedContentControl.HeaderProperty, multiBinding);
			TabControlExperiment.Items.Add(tabItemCloseable);
			ExperimentList.Add(experiment);
			return uCExperiment;
		}

		private void experiment_Event(object sender, EventArgs e)
		{
			Experiment experiment = sender as Experiment;
			PropertyChangedEventArgsEx propertyChangedEventArgsEx = e as PropertyChangedEventArgsEx;
			if (experiment != null && propertyChangedEventArgsEx != null && propertyChangedEventArgsEx.PropertyName == "Status" && experiment.Status == EExperimentStatus.Completed)
			{
				TabItem tabItem = (from TabItem s in TabControlExperiment.Items
					where s.Content is UCExperiment && ((UCExperiment)s.Content).Experiment == experiment
					select s).FirstOrDefault();
				if (tabItem != null)
				{
					TabControlExperiment.SelectedItem = tabItem;
				}
			}
		}

		private void item_CloseTab(object sender, RoutedEventArgs e)
		{
			UCExperiment uCExperiment = ((TabItemCloseable)sender).Content as UCExperiment;
			if (uCExperiment != null)
			{
				uCExperiment.Close();
			}
			e.Handled = true;
		}

		private void window_OnWindowClose(object sender, EventArgs e)
		{
			UCExperiment uCExperiment = sender as UCExperiment;
			if (uCExperiment != null)
			{
				uCExperiment.Experiment.UnLinkProject(false);
				ExperimentList.Remove(uCExperiment.Experiment);
				TabControlExperiment.Items.Remove(uCExperiment.Parent);
				foreach (TabItem item in (IEnumerable)TabControlExperiment.Items)
				{
					if (item.Content is UCExperiment && !string.IsNullOrEmpty(uCExperiment.Experiment.Device.Series))
					{
						Experiment experiment = ((UCExperiment)item.Content).Experiment;
						if (!string.IsNullOrEmpty(experiment.Device.Series) && experiment.Status != EExperimentStatus.Completed && experiment.Device.Series == uCExperiment.Experiment.Device.Series)
						{
							experiment.CanUseModelA = true;
							experiment.CanUseModelB = true;
							break;
						}
					}
				}
			}
			Utility.ClearMemory();
		}

		private void window_OnExperimentNew(object sender, CreateExperimentEventArgs e)
		{
			CreateExperiment(e.CreateMode);
		}

		private void listBoxHistoryExperimentTemplate_MouseDoubleClick(object sender, MouseButtonEventArgs e)
		{
		}

		private void OpenExperiment(string name)
		{
			Experiment experiment = Experiment.Load(name);
			if (experiment != null)
			{
				CreateNewTabItem(experiment);
			}
			else if (MessageBox.Show(Utility.GetMessage("msg_experiment_notexist"), Utility.GetMessage("Warning"), MessageBoxButton.YesNo, MessageBoxImage.Question, MessageBoxResult.Yes) == MessageBoxResult.Yes)
			{
				ConfigSettings.GetInstance().History.RemoveExperimentHistory(name);
			}
		}

		private void btnHelp_Click(object sender, RoutedEventArgs e)
		{
			string text = Utility.GetApplicationPath() + "Operator's Manual.pdf";
			if (File.Exists(text))
			{
				try
				{
					Process.Start(text);
					return;
				}
				catch (Exception ex)
				{
					MessageBox.Show(ex.Message);
					return;
				}
			}
			MessageBox.Show(Utility.GetMessage("msg_menuhelp_not_found"), Utility.GetMessage("Warning"), MessageBoxButton.OK, MessageBoxImage.Exclamation);
		}

		private void btnAbout_Click(object sender, RoutedEventArgs e)
		{
			Command_Version_Executed(this, null);
		}

		private void Command_TestPageVisible_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
		}

		private void Command_TestPageVisible_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			tabItemTest.Visibility = ((tabItemTest.Visibility == Visibility.Visible) ? Visibility.Collapsed : Visibility.Visible);
		}

		private void btnMinimize_Click(object sender, RoutedEventArgs e)
		{
			base.WindowState = WindowState.Minimized;
			Utility.ClearMemory();
		}

		private void btnClose_Click(object sender, RoutedEventArgs e)
		{
			Close();
		}

		private void Root_Loaded(object sender, RoutedEventArgs e)
		{
			isloaded = true;
		}

		public void OpenPcrFile(string uri)
		{
			if (worker == null)
			{
				worker = new BackgroundWorker();
				worker.WorkerReportsProgress = true;
				worker.ProgressChanged += worker_ProgressChanged;
				worker.DoWork += worker_DoWork;
				worker.RunWorkerAsync(new object[2] { this, uriList });
			}
			uriList.Add(uri);
		}

		private void worker_DoWork(object sender, DoWorkEventArgs e)
		{
			object[] array = e.Argument as object[];
			MainWindow mainWindow = array[0] as MainWindow;
			List<string> list = array[1] as List<string>;
			while (true)
			{
				if (!mainWindow.isloaded)
				{
					Thread.Sleep(10);
				}
				else if (list.Count > 0)
				{
					Thread.Sleep(10);
					((BackgroundWorker)sender).ReportProgress(100, list[0]);
					list.RemoveAt(0);
				}
			}
		}

		private void worker_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			string text = e.UserState as string;
			Experiment experiment = Experiment.Load(text);
			if (experiment == null)
			{
				experiment = ReadOldPcr.Read(text);
			}
			if (experiment != null)
			{
				CreateNewTabItem(experiment);
			}
			else
			{
				MessageBox.Show(Utility.GetMessage("msg_load_experiment_fail") + "\r\n" + text);
			}
		}

		public void SetHomeControl(UserControl HomeControl)
		{
			TabItemHome.Content = HomeControl;
		}

		private void linkAbout_Click(object sender, RoutedEventArgs e)
		{
			Hyperlink hyperlink = sender as Hyperlink;
			if (hyperlink == null || hyperlink.NavigateUri == null)
			{
				return;
			}
			try
			{
				Process.Start(hyperlink.NavigateUri.AbsoluteUri);
			}
			catch (Exception)
			{
			}
		}

		private void Command_HotlidTemperature_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			TabItem tabItem = mainTab.SelectedItem as TabItem;
			e.CanExecute = tabItem.Header.Equals(Utility.GetMessage("Tool")) && ucSettingMain.IsExperimentSettingTabSelected();
		}

		private void Command_HotlidTemperature_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			HotlidTemperatureSettingWindow hotlidTemperatureSettingWindow = new HotlidTemperatureSettingWindow();
			hotlidTemperatureSettingWindow.Owner = Utility.GetMainWindow();
			if (hotlidTemperatureSettingWindow.ShowDialog() != true)
			{
				return;
			}
			foreach (TypeTemperature hotlidTemperature in hotlidTemperatureSettingWindow.HotlidTemperatures)
			{
				ConfigSettings.GetInstance().BasicSetting.SetHotlidTemperature(hotlidTemperature.Type, hotlidTemperature.Temperature);
			}
		}

		private void Command_Version_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			e.CanExecute = true;
		}

		private void Command_Version_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			VesionWindow vesionWindow = new VesionWindow();
			vesionWindow.Owner = Utility.GetMainWindow();
			vesionWindow.ShowDialog();
		}

		private void Command_Fast_CanExecute(object sender, CanExecuteRoutedEventArgs e)
		{
			if (mainTab.SelectedIndex == 0 && TabControlExperiment.SelectedIndex > 0)
			{
				TabItem tabItem = TabControlExperiment.SelectedItem as TabItem;
				if (tabItem != null)
				{
					UCExperiment uCExperiment = tabItem.Content as UCExperiment;
					if (uCExperiment != null && uCExperiment.Experiment.Device.Fast)
					{
						e.CanExecute = true;
						return;
					}
				}
			}
			e.CanExecute = false;
		}

		private void Command_Fast_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			FastWindow fastWindow = new FastWindow();
			fastWindow.Owner = Utility.GetMainWindow();
			fastWindow.ShowDialog();
		}
	}
}
